from rest_framework.views import APIView
from .models import User
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveAPIView, UpdateAPIView
from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from django_redis import get_redis_connection

from .serializers import AddUserBrowseHistory
from . import serializers
from . import constants
from contents.crons import generate_static_index_html
from goods.models import SKU
from goods.serializers import SKUSerializer


# 验证用户名
class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }

        return Response(data)


# 验证手机号
class MobileCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            "count": count,
            "mobile": mobile
        }

        return Response(data)


# 注册
"""
CreateAPIView = GenericAPIView + CreateModelMixin
APIview没有校验；
GenericAPIView能校验，但是不能没有模型的保存动作；
CreateModelMixin，默认post请求，创建并保存模型数据；
CreateAPIView可以将GenericAPIView和CreateModelMixin结合起来
"""


class UserView(CreateAPIView):
    serializer_class = CreateUserSerializer


class UserDetailView(RetrieveAPIView):
    """提供登录用户的详情的"""

    serializer_class = UserDetailSerializer

    # IsAuthenticated 采用的是JWT的验证
    # 用户身份验证:是否是登录用户,如果未登录,验证就不通过;如果通过,重写get_object方法
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """
        返回当前谁是登录用户,
        为什么重写该方法:是因为我们的路由没有主键,
         返回的user是JWT验证系统验证后的登录用户.
        """
        return self.request.user


class EmailView(UpdateAPIView):
    """更新邮件"""

    # 验证用户身份信息
    permission_classes = [IsAuthenticated]
    # 指定序列化器
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    """验证邮件是否是真实的邮件"""

    def get(self, request):
        # 获取token
        token = request.query_params.get("token")
        if not token:
            return Response({"message": "缺少token"}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token,并返回user(将过程封装在User中是因为我们读的是user,这样方便,封装在utils中也行)
        #
        user = User.check_verify_email_token(token)
        if not user:
            return Response({"message": "无效token"}, status=status.HTTP_400_BAD_REQUEST)

        # 修改当前user的email_active属性的值为True
        user.email_active = True
        user.save()

        return Response({"message": "ok"})


class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    """
    what the fuck?
    验证用户是否登录,如果登录则执行下面代码?
    """
    permission = [IsAuthenticated]

    def get_queryset(self):
        generate_static_index_html()
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            "user_id": user.id,
            "default_address_id": user.default_address_id,
            "limit": constants.USER_ADDRESS_COUNTS_LIMIT,
            "addresses": serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({"message": "保存地址数据已达到上限"}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=["put"], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        :param request:
        :param pk:
        :param address_id:
        :return:
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({"message": "ok"}, status=status.HTTP_200_OK)

    @action(methods=["put"], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        :param request:
        :param pk:
        :param address_id:
        :return:
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserBrowsingHittoryView(CreateModelMixin, GenericAPIView):
    """
    用户浏览记录
    继承CreateModelMixin能保证post请求中create方法被执行.
    继承GenericAPIView,既支持post,又支持get.
    """
    """
    多继承,先执行前面的父类,
    serializer_class是写给CreateModelMixin的,post也是写给CreateModelMixin的,
    而CreateModelMixin根本不知道get是谁,不会执行它.
    get中的序列化器相当于是自己开了个小灶,自己炒菜(序列化),自己送外卖(返回值).
    """
    serializer_class = AddUserBrowseHistory
    # 验证用户登录
    permission_classes = [IsAuthenticated]

    # CreateAPIView:只会自动的创建post请求,而不会创建get.
    # 因为我们还需要在这个接口中实现浏览记录的查询.
    def post(self, request):
        # 接受参数sku_id,校验参数
        # 保存数据
        # 返回
        return self.create(request)

    # 因为我们还需要在这个接口中实现浏览记录的查询,所以不能只维护post,
    # 所以不适用CreateAPIView.
    def get(self, request):
        """查询用户浏览记录"""
        user_id = request.user.id

        redids_conn = get_redis_connection("history")
        # lrange(name, start, end)相当于字符串切片
        sku_ids = redids_conn.lrange("history_%s" % user_id, 0, -1)
        sku_list = []
        # 为了保持查询出的顺序与用户的浏览历史保存顺序一致
        # 遍历sku_ids,取出sku_id,查询sku
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        serializer_sku = SKUSerializer(sku_list, many=True)
        return Response(serializer_sku.data)


